package com.dearbinge.admin.client.openapi.controller.user;

import com.dearbinge.data.api.admin.AdminSecurityUserService;
import com.dearbinge.data.pojo.admin.AdminSecurityUser;
import com.dearbinge.utils.MD5s;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.enums.ResultStatusCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Api(tags = "2、用户CRUD")
@RestController
@RequestMapping("/user")
@CrossOrigin
@EnableAutoConfiguration
public class UserController extends WebMvcConfigurerAdapter  {

    @Autowired
    private AdminSecurityUserService adminSecurityUserService;



    @ApiOperation(value = "创建或更新用户(更新包括关停.删除)", notes = "创建或更新用户(更新包括关停.删除)")
    @RequestMapping(value = "/createOrUpdateUser", method = RequestMethod.POST)
    public ResultMsg<String> createUser(@RequestBody AdminSecurityUser adminSecurityUser) {
    	int data;
        try {
        	if(StringUtils.isEmpty(adminSecurityUser.getId())){
        		adminSecurityUser.setPassword(MD5s.execute(adminSecurityUser.getPassword()));
        		adminSecurityUser.setAccountNonLocked(1);
        		data = adminSecurityUserService.insert(adminSecurityUser);
        	}else{
        		data = adminSecurityUserService.updateByPrimaryKeySelective(adminSecurityUser);
        	}
        	if(data>0){
        		return ResultMsg.ok("ok");
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }

    @ApiOperation(value = "登录", notes = "登录")
    @RequestMapping(value = "/loginUser", method = RequestMethod.POST)
    public ResultMsg<String> loginUser(@RequestBody AdminSecurityUser adminSecurityUser) {
        try {
        	if(!StringUtils.isEmpty(adminSecurityUserService.loginUser(adminSecurityUser.getUsername(),MD5s.execute(adminSecurityUser.getPassword())))){
        		return ResultMsg.ok("ok");
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }



}
